function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);//匹配目标参数
    if (r != null) return (r[2]);
    return null; //返回参数值
}

function showMsg(msg) {
    if (msg) {
        mui.alert(msg);
    }
}


$(document).ready(function () {
    /*填写支付金额*/
    $("#createPay").click(function () {
        var money = $(".money>input").val().trim();
        money = money.split("￥")[1];
        // if (money < 10) {
        //     showMsg("支付金额最少10元");
        //     return;
        // }
        var oMask = $(".mask"), oPass = $(".pass");
        $.ajax({
            url: "/thmlfApi/avs/pay/getquickaccess"+"?_d="+Date.parse(new Date()),
            type: "POST",
            data: JSON.stringify({"customerId": sessionStorage.getItem("payerId")}),
            dataType: 'json',
            contentType: "application/json;charset=utf-8",
            success: function (r) {
                if (r.code != 200) {
                    showMsg(r.message);
                }
                else {
                    $('#pay_access').find('tr').remove();
                    var payAccessHtml = "";
                    // $.each(r.result,function (index,data) {
                    //     console.log(data,index);
                    // });
                    for (var i = 0; i < r.result.length; i++) {
                        payAccessHtml = '<tr onclick="toGetPay(\'' + r.result[i].payAccessId + '\')">' +
                            '<td>' + r.result[i].accessName + '</td>' +
                            '<td>当日</td>' +
                            '<td>' + r.result[i].rate + '%+' + r.result[i].deposit + '</td>' +
                            '<td>' + r.result[i].singleTime + '元</td>' +
                            '</tr>';
                        $("#pay_access").append(payAccessHtml);
                    }
                    oPass.fadeIn();
                    oMask.fadeIn();
                    oMask.one("click", function () {
                        oPass.fadeOut();
                        oMask.fadeOut();
                    });
                }
            }
        });

    });
    $(".pass .table > tbody > tr").each(function () {
        $(this).click(function () {
            var url = $(this).attr('data-link');
            window.open(url, "_self");
        })
    });

    var oIpt = $(".money input"),
        money = "",
        width = $('.table td').eq(0).width();
    $(".table td").each(function () {
        $(this).height(width);
        $(this).click(function () {
            oIpt.removeClass("no-input");
            var val = $(this).text();
            if (/\d/.test(val)) {
                if (money.indexOf(".") === -1 || money.indexOf(".") > money.length - 3) {
                    money += val;
                }
            } else if (/\./.test(val)) {
                if (!/\./.test(money)) {
                    money += ".";
                }
            } else if (/C/.test(val)) {
                money = money.slice(0, -1) || "0";
                if (/\.$/.test(money)) {
                    money = money.slice(0, -1);
                }
                if (money === "0") {
                    oIpt.addClass("no-input");
                }
            } else {
                money = money ? money : 0;
            }
            oIpt.val("￥" + parseFloat(money).toFixed(2));
        })
    });

    $(".trans-record > .panel-body").on("click", ".record-block", function () {
        var oInfo = $(".trans-record-info");
        var id = $(this).attr("orderId");
        oInfo.animate({left: 0}, "fast", "linear");
        oInfo.find(".go-back").one("click", function () {
            oInfo.animate({left: "100%"}, "fast", "linear");
        });
        $.ajax({
            url:"/thmlfApi/avs/pay/getpayreocrdinfo",
            type:"POST",
            data:{orderId:id},
            success:function (r) {
                if (r.code == 200){
                    var status = '';
                    switch (r.result.status){
                        case 1:
                            //等付款
                            status = '待付款';
                            break;
                        case 2:
                            //取消
                            status = '取消';
                            break;
                        case 3:
                            // 退款
                            status = '退款';
                            break;
                        case 4:
                            // 成功
                            status = '成功';
                            break;
                        case 6:
                            // 提现失败
                            status = '提现失败';
                            $('.record-info-block > button').show();
                            break;
                        case 7:
                            status = '提现成功';
                            break;
                        case 8:
                            status = '缴费成功';
                            break;
                    }
                    $('#money').text(r.result.amountTotal);
                    $('#orderStatus').text(status);
                    $('#orderNum').text(r.result.orderNum);
                    $('#orderDate').text(r.result.createDate);
                    $('#accessName').text(r.result.accessName);
                    $('#rate').text(r.result.serviceCost);
                    $('#moneys').text(r.result.realAmount);
                    $('#overDate').text(r.result.finishDate);
                    $('#cardNum').text(r.result.remark);
                }else
                    mui.alert(r.message);
            },
            error:function (e) {
                mui.alert("获取详情失败");
            }

        })
    });


    // 添加绑卡
    var oForm = $(".binding > form");
    oForm.find("button[type='submit']").click(function (e) {
        e.preventDefault();
        var bankName = oForm.find("[name='bankName']").val();
        var cardType = oForm.find("[name='cardType']").val();
        var holdName = oForm.find("[name='holdName']").val();
        var phone = oForm.find("[name='phone']").val();
        var cardNum = oForm.find("[name='cardNum']").val();
        $('#payerId').val(sessionStorage.getItem("payerId"));
        if (bankName == null) {
            showMsg("请选择结算银行");
            return false;
        }
        if (cardNum == null) {
            showMsg("请选择银行卡类型");
            return false;
        }
        if (holdName == null) {
            showMsg("请输入户主姓名");
            return false;
        }
        if (phone == null) {
            showMsg("请输入预留手机号");
            return false;
        }
        if (cardNum == null) {
            showMsg("请输入银行卡号");
            return false;
        } else if (!(/^\d{15,19}$/).test(cardNum)) {
            showMsg("银行卡号输入有误");
            return false;
        }
        $.ajax({
            url: "/thmlfApi/avs/pay/adddepositcard",
            type: "POST",
            cache: false,
            data: oForm.serialize(),
            success: function (r) {
                if (r.code == 200) {
                    mui.alert("绑卡成功!");
                    window.history.back();
                } else
                    mui.alert(r.message);
            },
            error: function (e) {
                console.log("request error:" + e);
                showMsg("网络错误，请稍后再试");
            }
        });
    });

    // 点击编辑按钮
    var editFlag = false;
    $("#editCard").click(function () {
        editFlag = !editFlag;
        $(this).toggleClass("btn-primary");
        $(this).toggleClass("btn-danger");
        if (editFlag) {
            $(this).text("完成");
        } else {
            $(this).text("编辑")
        }
        if (editFlag) {
            $(".card-block").each(function () {
                $(this).click(function () {
                    $(this).toggleClass("editable");
                    $(this).siblings().removeClass("editable");
                });
            })
        }
    });

    // 重新发起提现
    $('.record-info-block > button').click(function () {
        var data = {"payerId":sessionStorage.getItem("payerId"),"orderNum":$('#orderNum').text(),"amount":$('#money').text(),"summary":$('#cardNum').text()};
        $.ajax({
            url:'/thmlfApi/avs/pay/deposit'+"?_d="+Date.parse(new Date()),
            type:'POST',
            data:JSON.stringify(data),
            dataType:'JSON',
            contentType:"application/json",
            success:function (r) {
                if (r.code == 200){
                    window.location.reload();
                }else
                    mui.alert(r.message);
            },
            error:function (e) {
                mui.alert("请求失败，请重试");
            }

        })
    });


    // 删除绑定卡
    $(".settlement-card > .body").on("click", ".card-block > .remove-card", function () {
        var card = $(this).parent();
        var tail = $(this).next().next().next().children().eq(3).text();
        // confirmMsg();
        var bindId = $(this).attr('cash-bind-id');
        var isSettle=card.attr("data-settle");
        if (isSettle){
            mui.alert("请先解除结算卡绑定");
            return;
        }
        mui.confirm("您确定要删除尾号为" + tail + "的银行卡吗？", "提示", ["确定", "取消"], function () {
            $.ajax({
                url: "/thmlfApi/avs/pay/deldepositcard?payerId=" + sessionStorage.getItem("payerId") + "&cashBindId=" + bindId+"&_d="+Date.parse(new Date()),
                type: "GET",
                cache: false,
                success: function (r) {
                    if (r.code == 200) {
                        console.log("delete success");
                        card.remove();
                        showMsg("成功删除");
                    } else {
                        showMsg(r.message);
                    }
                },
                error: function () {
                    mui.alert("请求失败，请重试");
                }
            });
        });
    });
});

//发起支付
function toGetPay(gatewayId,moneyVal,remark) {
    var money;
    if (moneyVal == undefined || moneyVal == null)
        money = $(".money>input").val().trim();
    else
        money = "￥"+moneyVal;
    money = money.split("￥")[1];
    var remarkVar;
    if (remark == undefined || remark == null)
        remarkVar = "极速收款";
    else
        remarkVar = "VIP缴费";
    var params = {
        "payerId": sessionStorage.getItem("payerId"),
        "remark": remarkVar,
        "appId":sessionStorage.getItem("appId"),
        "amount": money,
        "gatewayId": gatewayId,
        "payType": "2",
        "orderIp": sessionStorage.getItem("ipAddress"),
        "orderType":remark == '1' ? 'vip' : 'cash'
    };
    $.ajax({
        url: "/thmlfApi/avs/pay/createpayorder"+"?_d="+Date.parse(new Date()),
        type: "POST",
        data: JSON.stringify(params),
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (r) {
            if (r.code == '20016')
                sessionStorage.setItem('vip', 'no');
            if (r.code != 200) {
                showMsg(r.message);
            } else {
                var payerId = r.result.payerId;
                var orderNum = r.result.orderNum;
                var gateway = r.result.gateway;
                var URL = r.result.URL;
                if (URL.indexOf("?") !== -1){
                    URL = URL + "&";
                }else {
                    URL = URL + "?";
                }
                window.location.href = URL + "amount="+money+"&payerId="+payerId+"&orderNum="+orderNum+"&gateway="+gateway+"&_d="+Date.parse(new Date());
            }
        },
        error:function (e) {
            mui.toast('服务器繁忙，请稍后重试');
            // alert(sessionStorage.getItem('appId'));
        }
    });
}

function toPay() {
    if (sessionStorage.getItem('vip') != 'yes'){
        mui.confirm("使用此功能需要缴费成为VIP后，才可使用。", "提示", ["缴费", "取消"], function (e) {
            var w = null;
            if (e.index == 0){
                // w = plus.nativeUI.showWaiting();
                // 显示VIP缴费通道
                // showVipPay();
                // vip缴费
                vipPayment();
            }
        });
        return;
    }
    window.location.href="/pay/get-pay.html"
}

// 显示VIP缴费通道
function showVipPay() {
    $.ajax({
        url: "/thmlfApi/avs/pay/getquickaccess"+"?_d="+Date.parse(new Date()),
        type: "POST",
        data: JSON.stringify({"customerId": sessionStorage.getItem("payerId")}),
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (r) {
            // w.close();
            if (r.code != 200) {
                showMsg(r.message);
            }
            else {
                $("#actionsheet").find("li").remove();
                $.each(r.result,function (index,data) {
                    var item = '<li class="mui-table-view-cell">'+
                        '<a href="#" onclick="toGetPay(\''+data.payAccessId+'\',\''+vipMoney+'\',\''+1+'\')">'+data.accessName+'</a>'+
                        '</li>';
                    $("#actionsheet").append(item);
                });
                mui('#picture').popover('toggle');
            }
        }
    });
}

function toBankBindList() {
    window.location.href="/pay/card-manage.html"
}

function toRecord() {
    window.location.href = "/pay/record.html";
}